package com.whyl.eems.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 日期处理
 * 
 */
public class DateUtils {
	private final static Logger logger = LoggerFactory.getLogger(DateUtils.class);
	/** 时间格式(yyyy-MM-dd) */
	public final static String DATE_PATTERN = "yyyy-MM-dd";
	/** 时间格式(yyyy-MM-dd HH:mm:ss) */
	public final static String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";

	public static String format(Date date) {
		return format(date, DATE_PATTERN);
	}

	public static String formatTime(Date date) {
		return format(date, DATE_TIME_PATTERN);
	}

	/**
	 * 时间加一年
	 * @param
	 * @return
	 */
	public static String getNextDate(Date time) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date());
		calendar.add(Calendar.YEAR, +1);
		Date date = calendar.getTime();
		return format(date, DATE_TIME_PATTERN);
	}

	/**
	 * 时间加N天
	 * @param
	 * @return
	 */
	public static Date getNextDay(Date time,Integer day) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(time);
		calendar.add(Calendar.DAY_OF_MONTH, +day);
		return calendar.getTime();
	}

	/**
	 * 时间加N分钟
	 * @param
	 * @return
	 */
	public static Date getNextMin(Date time,Integer min) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(time);
		calendar.add(Calendar.MINUTE, +min);
		return calendar.getTime();
	}

	public static String format(Date date, String pattern) {
		if (date != null) {
			SimpleDateFormat df = new SimpleDateFormat(pattern);
			return df.format(date);
		}
		return null;
	}

	public static Date dateTimeFormat(String date) {
		try {
			if (date != null) {
				SimpleDateFormat df = new SimpleDateFormat(DATE_TIME_PATTERN);
				return df.parse(date);
			}else {
				return null;
			}
		} catch (ParseException e) {
			e.printStackTrace();
			return null;
		}
	}

	public static String getTimeBefore(Date date) {
		Date now = new Date();
		long l = now.getTime() - date.getTime();
		long day = l / (24 * 60 * 60 * 1000);
		long hour = (l / (60 * 60 * 1000) - day * 24);
		long min = ((l / (60 * 1000)) - day * 24 * 60 - hour * 60);
		long s = (l / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
		String r = "";
		if (day > 0) {
			r +=day + "天";
		}
		if (hour > 0) {
			r +=hour + "小时";
		}
		if (min > 0) {
			r +=min + "分";
		}
		if (s > 0) {
			r +=s + "秒";
		}
		r += "前";
		return r;
	}

	public static Long getTimeMin(Date dayTime,String hardwareTime){
		Long min = new Long(-1);
		try {
			SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
			Date parseHardwareTime = df.parse(hardwareTime);
			long minTime = dayTime.getTime() - parseHardwareTime.getTime();
			min = minTime / (60 * 1000);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return min;
	}

	public static Long getTimeSecond(Date date){
		return date.getTime() / 1000;
	}
}
